package run.bottle.shiro.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import run.bottle.shiro.model.dto.Result;
import run.bottle.shiro.model.entity.SysUser;
import run.bottle.shiro.service.SysUserService;
import run.bottle.shiro.utils.JWTUtil;
import run.bottle.shiro.utils.MD5Utils;
import run.bottle.shiro.utils.ShiroUtils;

@Api(tags = "登陆登出控制器")
@Controller
@RequestMapping("/sys")
public class LoginController {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    private final SysUserService sysUserService;

    public LoginController(SysUserService sysUserService) {
        this.sysUserService = sysUserService;
    }


    @ApiOperation("登陆接口")
    @PostMapping("/login")
    @ResponseBody
    public Result login(@RequestParam("username") String username,
                        @RequestParam("password") String password){
        log.info("登陆账户："+username+"--登陆密码："+password);
        try{
            password = MD5Utils.encrypt(username, password);
            SysUser user = sysUserService.getUser(username);

            if (user == null) {
                return Result.error("账户不存在");
            }

            if(!password.equals(user.getPassword())) {
                return Result.error("密码不正确");
            }

            String token = JWTUtil.createToken(username);
            log.info("登录成功");
            return Result.ok("登录成功", token);
        }catch (Exception e) {
            e.printStackTrace();
            log.info("登录失败");
            return Result.error("登录失败");
        }
    }

    @ApiOperation("注册接口")
    @PostMapping("/register")
    @ResponseBody
    public Result register(SysUser user){
        System.out.println(user.getMobile());
        return Result.ok("注册成功,去登陆");
    }

    @ApiOperation("登出接口")
    @GetMapping("/logout")
    public Result logout(){
        ShiroUtils.logout();
        return  Result.ok("注销成功!");
    }
}
